import Polygon from './Polygon'
import { Viewer, Entity, JulianDate, Cartesian3, CallbackProperty } from 'cesium'
import * as mu from '../mapUtil'
import * as turf from '@turf/turf'


export default class ThreePointRectangle extends Polygon {

  maxPointNum = 3
  minPointNum = 3

  options: {} = { units: 'kilometers' }

  constructor(p: {}, viewer: Viewer, layer: Entity) {
    super({type: '3点矩形', ...p}, viewer, layer)
  }

  calcuteShape(points: Entity[], time: JulianDate): (Cartesian3 | undefined)[] {
    switch (points.length) {
      case 0: return []
      case 1: return []
      case 2: return []
      case 3: {
        let posis = points.map(ent => ent.position.getValue(time))
        let turfPoints = posis.map(cartesian3 => {
          let longLat = mu.cartesian2lonlat(cartesian3)
          return turf.point(longLat)
        })
        let p1 = turfPoints[0]
        let p2 = turfPoints[1]
        let px = turfPoints[2]
        let bear0 = turf.bearing(p1, p2, this.options)
        let line0 = turf.lineString([turf.getCoord(p1), turf.getCoord(p2)], this.options)
        let distance = turf.pointToLineDistance(px, line0, {method: 'planar', ... this.options})
        let direction = turf.booleanClockwise(turf.lineString([p1, p2, px, p1].map(p => turf.getCoord(p))))
        let p3 = turf.destination(p2, distance, bear0 + (direction? 90 : -90), this.options)
        let p4 = turf.destination(p1, distance, bear0 + (direction? 90 : -90), this.options)
        return [p1, p2, p3, p4].map( tgt => mu.lonlat2Cartesian(turf.getCoord(tgt)))
      }
    }
  }

  override initTempShape(): void {
    this.addTempLine(new CallbackProperty((time, result) => {
      return this.ctls.map(ent => ent.position?.getValue(time))
    }, false))
  }

}
